package com.zhangsr.zus.remoting.api.transport;

import com.zhangsr.zus.remoting.api.Channel;
import com.zhangsr.zus.remoting.api.ChannelHandler;
import com.zhangsr.zus.remoting.api.Decodeable;
import com.zhangsr.zus.remoting.api.exception.RemotingException;
import com.zhangsr.zus.remoting.api.exchange.Request;
import com.zhangsr.zus.remoting.api.exchange.Response;
import org.apache.log4j.Logger;

/**
 * @Author: zhangsr
 */
public class DecodeHandler extends AbstractChannelHandlerDelegate {

    private static final Logger logger = Logger.getLogger(ChannelHandlerDispatcher.class);

    public DecodeHandler(ChannelHandler handler) {
        super(handler);
    }

    public void received(Channel channel, Object message) throws RemotingException {
        if (message instanceof Decodeable) {
            decode(message);
        }

        if (message instanceof Request) {
            decode(((Request) message).getData());
        }

        if (message instanceof Response) {
            decode(((Response) message).getResult());
        }

        handler.received(channel, message);
    }

    private void decode(Object message) {
        if (message != null && message instanceof Decodeable) {
            try {
                ((Decodeable) message).decode();
                if (logger.isDebugEnabled()) {
                    logger.debug(new StringBuilder(32).append("Decode decodeable message ")
                            .append(message.getClass().getName()).toString());
                }
            } catch (Throwable e) {
                logger.warn(new StringBuilder(32).append("Call Decodeable.decode failed: ").append(e.getMessage()).toString(), e);
            }
        } // ~ end of catch
    } // ~ end of if
} // ~ end of method decode
